<template>
    <div class="defect-yield-container">
      <!-- Header / Search Area -->
      <div class="header-panel">
        <div class="time-selection">
          <span class="label">连退生产结束时间:</span>
          <el-date-picker
            v-model="searchParams.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期时间"
            end-placeholder="结束日期时间"
            class="custom-date-picker"
            size="small"
          />
        </div>
        <div class="summary-stats">
          <span>成品总重量: {{ summary.finishedWeight }} [t]</span>
          <span>原料总重量: {{ summary.rawWeight }} [t]</span>
          <span>O5板成材率: {{ summary.yieldRate }}</span>
        </div>
        <div class="search-actions">
          <button class="btn query-btn" @click="handleSearch">查询</button>
          <button class="btn reset-btn" @click="handleReset">重置</button>
          <button class="btn export-btn">导出</button>
        </div>
      </div>
  
      <!-- Statistics Area -->
      <div class="stats-panel">
        <div class="chart-section yield-chart-section">
          <div class="chart-header">O5板成材率</div>
          <div class="chart-body" ref="yieldGaugeRef"></div>
        </div>
        <div class="chart-section defect-gauge-section">
          <div class="chart-header">O5板缺陷统计</div>
          <div class="chart-body" ref="defectGaugeRef"></div>
        </div>
        <div class="chart-section defect-bar-section">
           <div class="chart-header">O5板缺陷统计</div>
          <div class="chart-body" ref="defectBarRef"></div>
        </div>
      </div>
  
      <!-- Table Area -->
      <div class="table-panel">
        <el-table
          :data="pagedTableData"
          style="width: 100%;"
          height="100%"
          border
          highlight-current-row
          size="small"
          :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '4px 8px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
          :cell-style="{ padding: '4px 8px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
          :row-style="{ background: '#0f2142' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" fixed="left" />
          <el-table-column prop="hotRollNo" label="热卷号" width="120" />
          <el-table-column prop="picklingExitRollNo" label="酸轧出口卷号" width="140" />
          <el-table-column prop="annealingExitRollNo" label="连退出口卷号" width="140" />
          <el-table-column prop="annealingWeight" label="连退重量[t]" width="100" />
          <el-table-column prop="coverRollExitNo" label="罩卷出口卷号" width="140" />
          <el-table-column prop="coverRollWeight" label="罩卷重量[t]" width="100" />
          <el-table-column prop="finishedWeight" label="成品重量[t]" width="100" />
          <el-table-column prop="rawMaterialWeight" label="原料重量[t]" width="100" />
          <el-table-column prop="annealingEndTime" label="连退生产结束时间" width="160" />
          <el-table-column prop="planNo" label="计划号" width="100" />
          <el-table-column prop="contractNo" label="合同号" width="120" />
          <el-table-column prop="steelGradeLevel" label="钢牌号(等级)" width="120" />
          <el-table-column prop="copperCode" label="铜质代码" width="100" />
          <el-table-column prop="materialThickness" label="材料厚度[mm]" width="110" />
          <el-table-column prop="materialWidth" label="材料宽度[mm]" width="110" />
          <el-table-column prop="surfaceLevel" label="表面级别" width="90" />
          <el-table-column prop="sortingLevel" label="分选等级" width="90" />
          <el-table-column prop="mainDefectCode" label="主缺陷代码" width="100" />
        </el-table>
      </div>
  
      <!-- Pagination Area -->
      <div class="pagination-panel">
        <el-pagination
           v-model:current-page="pagination.currentPage"
           v-model:page-size="pagination.pageSize"
           :page-sizes="[10, 20, 30, 50]"
           layout="total, sizes, prev, pager, next, jumper"
           :total="pagination.total"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           background
           small
         />
      </div>
  
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  import {
    GaugeChart,
    BarChart
  } from 'echarts/charts';
  import {
    TooltipComponent,
    GridComponent,
    LegendComponent
  } from 'echarts/components';
  import {
    CanvasRenderer
  } from 'echarts/renderers';
  
  // Register ECharts components
  echarts.use([
    TooltipComponent,
    GridComponent,
    LegendComponent,
    GaugeChart,
    BarChart,
    CanvasRenderer
  ]);
  
  // --- Interfaces --- 
  interface SearchParams {
    dateRange: Date[];
  }
  
  interface SummaryStats {
    finishedWeight: string;
    rawWeight: string;
    yieldRate: string;
  }
  
  interface TableRow {
    id: number;
    hotRollNo: string;
    picklingExitRollNo: string;
    annealingExitRollNo: string;
    annealingWeight: number;
    coverRollExitNo?: string;
    coverRollWeight?: number;
    finishedWeight: number;
    rawMaterialWeight: number;
    annealingEndTime: string;
    planNo: string;
    contractNo: string;
    steelGradeLevel: string;
    copperCode: string;
    materialThickness: number;
    materialWidth: number;
    surfaceLevel: number;
    sortingLevel: number;
    mainDefectCode: string;
  }
  
  // --- Reactive State --- 
  const searchParams = reactive<SearchParams>({
    dateRange: [new Date('2024-02-20 23:19:00'), new Date('2024-03-06 23:19:00')] // Default from image
  });
  
  const summary = reactive<SummaryStats>({
    finishedWeight: '3962.81',
    rawWeight: '4324.73',
    yieldRate: '91.63 %'
  });
  
  // --- Mock Table Data --- 
  const allTableData = ref<TableRow[]>(Array.from({ length: 500 }, (_, i) => {
    const baseId = 142000000 + i * 1000;
    const hasCoverRoll = i % 10 === 6 || i % 10 === 9; // Simulate some rows having cover roll data
    return {
      id: i + 1,
      hotRollNo: `R09${String(8001700 + i * 10000).slice(-7)}`,
      picklingExitRollNo: `H${baseId + 10000000}`, 
      annealingExitRollNo: `H${baseId + 20000000}`, 
      annealingWeight: parseFloat((9.13 + Math.random() * 0.1).toFixed(2)), 
      coverRollExitNo: hasCoverRoll ? `H${baseId + 30000000}` : '',
      coverRollWeight: hasCoverRoll ? parseFloat((7.08 + Math.random() * 0.5).toFixed(2)) : undefined,
      finishedWeight: parseFloat((28.76 + Math.random() * 0.2).toFixed(2)),
      rawMaterialWeight: parseFloat((28.87 + Math.random() * 0.1).toFixed(2)),
      annealingEndTime: `2024-03-04 0${String(3 + Math.floor(i/60)).padStart(1, '0')}:${String(i%60).padStart(2,'0')}:${String(Math.floor(Math.random()*60)).padStart(2,'0')}`,
      planNo: `A${String(5244309 + i).padStart(7,'0')}`,
      contractNo: `E${String(2430218000 + i * 100).padStart(10,'0')}`,
      steelGradeLevel: 'DC06',
      copperCode: 'CB013AWW',
      materialThickness: 0.65,
      materialWidth: 1615,
      surfaceLevel: 50,
      sortingLevel: i % 3 === 0 ? 0 : (i % 5 === 1 ? 10 : 20),
      mainDefectCode: i % 7 === 0 ? 'A00' : (i % 4 === 1 ? 'E20' : 'B00')
    };
  }));
  
  // --- Pagination --- 
  const pagination = reactive({
    currentPage: 1,
    pageSize: 22, // Match image roughly
    total: allTableData.value.length
  });
  
  const pagedTableData = computed(() => {
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    return allTableData.value.slice(start, end);
  });
  
  const indexMethod = (index: number) => {
    return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
  };
  
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    pagination.currentPage = 1;
  };
  
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
  };
  
  // --- ECharts Refs --- 
  const yieldGaugeRef = ref<HTMLElement | null>(null);
  const defectGaugeRef = ref<HTMLElement | null>(null);
  const defectBarRef = ref<HTMLElement | null>(null);
  
  // --- ECharts Instances --- 
  let yieldGaugeInstance: echarts.ECharts | null = null;
  let defectGaugeInstance: echarts.ECharts | null = null;
  let defectBarInstance: echarts.ECharts | null = null;
  
  // --- ECharts Options --- 
  const yieldGaugeOption = computed(() => ({
    series: [
      {
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '95%',
        startAngle: 200,
        endAngle: -20,
        min: 0,
        max: 100,
        splitNumber: 5,
        progress: {
          show: true,
          width: 18,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#58D6F8' }, // Light Blue
                { offset: 1, color: '#2AF598' }  // Green
            ])
          }
        },
        pointer: { show: false },
        axisLine: {
          lineStyle: {
            width: 18,
            color: [[1, 'rgba(44, 62, 80, 0.6)']]
          }
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        anchor: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 28,
          fontWeight: 'bold',
          offsetCenter: [0, '-5%'],
          color: '#2AF598',
          formatter: '{value}%'
        },
        data: [
          { value: parseFloat(summary.yieldRate) || 0 }
        ]
      }
    ]
  }));
  
  const defectGaugeOption = computed(() => ({
      tooltip: {
          formatter: '{a} <br/>{b} : {c}'
      },
      series: [
          {
              name: '缺陷统计',
              type: 'gauge',
              center: ['50%', '60%'],
              radius: '95%',
              min: 0,
              max: 300,
              splitNumber: 6,
              axisLine: {
                  lineStyle: {
                      width: 15,
                      color: [
                          [178/300, '#1890FF'],
                          [(178+38)/300, '#FAAD14'],
                          [(178+38+23)/300, '#F5222D'],
                          [1, '#D9D9D9']
                      ]
                  }
              },
              pointer: { show: false },
              axisTick: { show: false },
              splitLine: { show: false },
              axisLabel: { show: false },
              anchor: { show: false },
              title: { show: false },
              detail: {
                  valueAnimation: true,
                  formatter: '{value}\n总数',
                  color: '#fff',
                  fontSize: 28,
                  fontWeight: 'bold',
                  offsetCenter: ['0', '-5%']
              },
              data: [
                  { value: 242 }
              ]
          }
      ]
  }));
  
  const defectBarOption = computed(() => ({
      tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
      },
      grid: {
          left: '5%',
          right: '10%',
          bottom: '5%',
          top: '10%',
          containLabel: true
      },
      xAxis: {
          type: 'value',
          axisLabel: { color: '#c0c4cc', fontSize: 10 },
          splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
          axisLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } }
      },
      yAxis: {
          type: 'category',
          data: ['辊印', '夹杂', '纵向基纹', '表面其他'],
          axisLabel: { color: '#c0c4cc', fontSize: 10 },
          axisLine: { show: true, lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
          axisTick: { show: false }
      },
      series: [
          {
              name: '缺陷数量',
              type: 'bar',
              data: [3, 23, 38, 178],
              barWidth: '50%',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                   { offset: 0, color: '#1890FF' },
                   { offset: 1, color: '#53a8ff' }
                 ]),
                borderRadius: [0, 2, 2, 0]
              },
              label: {
                  show: true,
                  position: 'right',
                  color: '#fff',
                  fontSize: 11
              }
          }
      ]
  }));
  
  // --- ECharts Init & Update --- 
  const initCharts = () => {
    try {
      if (yieldGaugeRef.value && !yieldGaugeInstance) {
        yieldGaugeInstance = echarts.init(yieldGaugeRef.value);
        yieldGaugeInstance.setOption(yieldGaugeOption.value);
      }
      if (defectGaugeRef.value && !defectGaugeInstance) {
        defectGaugeInstance = echarts.init(defectGaugeRef.value);
        defectGaugeInstance.setOption(defectGaugeOption.value);
      }
      if (defectBarRef.value && !defectBarInstance) {
        defectBarInstance = echarts.init(defectBarRef.value);
        defectBarInstance.setOption(defectBarOption.value);
      }
    } catch (error) {
      console.error("ECharts initialization failed:", error);
    }
  };
  
  const resizeCharts = () => {
    yieldGaugeInstance?.resize();
    defectGaugeInstance?.resize();
    defectBarInstance?.resize();
  };
  
  // --- Lifecycle Hooks --- 
  onMounted(() => {
    nextTick(initCharts);
    window.addEventListener('resize', resizeCharts);
  });
  
  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts);
    yieldGaugeInstance?.dispose();
    defectGaugeInstance?.dispose();
    defectBarInstance?.dispose();
  });
  
  // --- Handlers --- 
  const handleSearch = () => {
    console.log('查询参数:', searchParams);
    // Add search logic
  };
  
  const handleReset = () => {
    searchParams.dateRange = [];
    console.log('重置参数');
    // Add reset logic
  };
  
  </script>
  
  <style scoped>
  /* --- Base Styles --- */
  .defect-yield-container {
    background-color: #0a1a3a; /* Match image dark blue */
    color: #c0c4cc;
    padding: 10px; /* Consistent padding */
    height: 100vh; /* Full viewport height */
    box-sizing: border-box;
    font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
    font-size: 13px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  /* --- Header Panel --- */
  .header-panel {
    background-color: #142a52; /* Darker blue background */
    padding: 8px 15px;
    border-radius: 4px;
    margin-bottom: 10px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap; /* Allow wrapping */
    border: 1px solid #2a5caa; /* Border like image panels */
  }
  
  .time-selection {
    display: flex;
    align-items: center;
  }
  
  .time-selection .label {
    margin-right: 8px;
    white-space: nowrap;
    font-size: 13px; /* Slightly larger label */
    color: #a2cfff; /* Lighter blue label */
  }
  
  /* Style Date Picker like image */
  :deep(.custom-date-picker.el-date-editor) {
    width: 260px !important; /* Wider */
    height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    border-radius: 3px !important;
  }
  :deep(.custom-date-picker .el-range-input) {
    background-color: transparent !important;
    color: #a2cfff !important;
    font-size: 13px !important;
    height: 26px !important;
    line-height: 26px !important;
  }
  :deep(.custom-date-picker .el-range-separator) {
    color: #a2cfff !important;
    font-size: 13px !important;
    line-height: 26px !important;
    padding: 0 2px;
  }
  :deep(.custom-date-picker .el-input__icon) {
    line-height: 28px;
    color: #409eff; /* Use a distinct icon color */
    font-size: 13px;
  }
  
  .summary-stats {
    display: flex;
    align-items: center;
    gap: 25px; /* Increased gap */
    font-size: 13px;
    flex-grow: 1;
    justify-content: center;
    color: #a2cfff; /* Match label color */
    margin: 5px 10px;
  }
  
  .summary-stats span span { /* Target the value part if needed */
    color: #fff; /* Make values white */
    font-weight: 500;
  }
  
  /* Style Buttons like image */
  .btn {
    height: 28px;
    padding: 0 18px;
    border: none;
    border-radius: 3px;
    font-size: 13px;
    cursor: pointer;
    margin-left: 10px;
    color: #fff;
    transition: background-color 0.2s ease;
  }
  .query-btn { background-color: #1890FF; box-shadow: 0 0 5px rgba(24, 144, 255, 0.5); }
  .query-btn:hover { background-color: #40a9ff; }
  .reset-btn { background-color: #5a7aa4; box-shadow: 0 0 5px rgba(90, 122, 164, 0.4); }
  .reset-btn:hover { background-color: #7b97c2; }
  .export-btn { background-color: #FAAD14; box-shadow: 0 0 5px rgba(250, 173, 20, 0.5); }
  .export-btn:hover { background-color: #ffc53d; }
  
  /* --- Statistics Panel --- */
  .stats-panel {
    display: flex;
    gap: 10px; /* Reduced gap */
    margin-bottom: 10px; /* Consistent margin */
    flex-shrink: 0;
    height: 200px; /* Fixed height like image */
  }
  
  .chart-section {
    background-image: url('../assets/img/itme_bg.png'); /* Use background image */
    background-size: cover;
    background-position: center;
    border: 1px solid #2a5caa; /* Match header border */
    border-radius: 8px; /* Increase border-radius */
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  /* Style Chart Headers like image */
  .chart-header {
    padding: 6px 15px; /* Adjusted padding */
    background-image: url('../assets/img/sub_title_bg.png'); /* Use title bg */
    background-size: 100% 100%;
    background-repeat: no-repeat;
    border-bottom: none; /* Remove border from header */
    text-align: center;
    font-weight: bold;
    color: #A2DFFF; /* Match title text color */
    font-size: 14px;
    flex-shrink: 0;
    line-height: 1.5;
  }
  
  .chart-body {
    flex-grow: 1;
    min-height: 120px; /* Adjust min height */
    padding: 5px; /* Reduced padding */
  }
  
  /* Specific chart section sizing */
  .yield-chart-section { flex: 3; } /* Adjust flex ratios */
  .defect-gauge-section { flex: 3; }
  .defect-bar-section { flex: 4; }
  
  /* --- Table Panel --- */
  .table-panel {
    flex-grow: 1;
    min-height: 0;
    overflow: hidden;
    background-image: url('../assets/img/itme_bg.png'); /* Use background image */
    background-size: cover;
    background-position: center;
    padding: 10px; /* Add padding */
    border: 1px solid #2a5caa; /* Match header border */
    border-radius: 4px;
    display: flex;
  }
  
  /* --- Table Styles (Deep) --- */
  :deep(.el-table) {
    background-color: transparent !important;
  }
  :deep(.el-table th.el-table__cell) {
    background-color: #2a5caa !important; /* Header background from image */
    color: #A2DFFF !important; /* Header text color */
    padding: 6px 0 !important; /* Adjust header padding */
    border-color: #06279d !important;
    font-weight: normal !important;
    text-align: center;
  }
  :deep(.el-table td.el-table__cell) {
    padding: 5px 0 !important; /* Adjust cell padding */
    border-color: #06279d !important;
    text-align: center;
    font-size: 12px; /* Smaller font */
    color: #c0c4cc;
  }
  :deep(.el-table tr) {
    background-color: transparent !important; /* Ensure row itself is transparent */
  }
  :deep(.el-table__body tr:nth-child(odd)) {
    background-color: #0f2142 !important; /* Dark blue odd rows */
  }
  :deep(.el-table__body tr:nth-child(even)) {
    background-color: #142a52 !important; /* Lighter blue even rows */
  }
  :deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
    /* background-color: inherit !important; */ /* Remove no hover effect */
    background-color: rgba(66, 180, 255, 0.15) !important; /* Apply semi-transparent blue on hover */
  }
  
  /* Apply same style to current selected row */
  :deep(.el-table__body tr.current-row > td.el-table__cell) {
    background-color: rgba(66, 180, 255, 0.15) !important;
  }
  
  /* Borders */
  :deep(.el-table--border .el-table__inner-wrapper::after),
  :deep(.el-table--border::after),
  :deep(.el-table--border::before) {
    background-color: #06279d !important;
  }
  :deep(.el-table td.el-table__cell),
  :deep(.el-table th.el-table__cell.is-leaf) {
    border-bottom: 1px solid #06279d !important;
  }
  :deep(.el-table--border td.el-table__cell),
  :deep(.el-table--border th.el-table__cell) {
    border-right: 1px solid #06279d !important;
  }
  :deep(.el-table__border-left-patch) {
     background-color: #06279d !important;
  }
  :deep(.el-table .el-table__cell) {
    border-color: #06279d !important; /* General border color */
  }
  :deep(.el-table--border) {
    border: 1px solid #06279d !important; /* Ensure outer border color */
  }
  :deep(.el-table:before) { /* Hide default bottom border line */
    display: none;
  }
  
  /* --- Pagination Panel --- */
  .pagination-panel {
    background-color: #142a52; /* Match header bg */
    padding: 5px 10px;
    border-radius: 4px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;
    margin-top: 10px;
    border: 1px solid #2a5caa;
  }
  /* Deep pagination styles */
  :deep(.el-pagination) { --el-pagination-bg-color: transparent; --el-pagination-text-color: #c0c4cc; --el-pagination-button-disabled-bg-color: transparent; --el-pagination-button-bg-color: transparent; --el-pagination-hover-color: #409eff; }
  :deep(.el-pager li) { border: 1px solid #2a5caa; margin: 0 3px; border-radius: 3px; min-width: 24px; height: 24px; line-height: 22px; font-size: 12px; }
  :deep(.el-pager li.is-active) { background-color: #1890FF; border-color: #1890FF; color: #fff; }
  :deep(.el-pagination button) { border: 1px solid #2a5caa; margin: 0 3px; border-radius: 3px; min-width: 24px; height: 24px; padding: 0 6px; }
  :deep(.el-pagination button:disabled) { border-color: #2a5caa; opacity: 0.5; }
  :deep(.el-pagination__jump) { color: #c0c4cc; margin-left: 10px; font-size: 13px; }
  :deep(.el-pagination__jump .el-input__wrapper) { background: #0a1a3a !important; border: 1px solid #2a5caa !important; box-shadow: none !important; height: 24px; width: 40px; border-radius: 3px; padding: 0 3px; }
  :deep(.el-pagination__jump .el-input__inner) { color: #c0c4cc !important; height: 22px !important; line-height: 22px !important; text-align: center; font-size: 12px !important; }
  :deep(.el-pagination__total) { color: #c0c4cc; margin-right: 10px; font-size: 13px; }
  :deep(.el-pagination__sizes) { margin-right: 10px; }
  :deep(.el-pagination__sizes .el-select .el-input__wrapper) { background: #0a1a3a !important; border: 1px solid #2a5caa !important; box-shadow: none !important; height: 24px; width: 90px; border-radius: 3px; padding: 0 3px; }
  :deep(.el-pagination__sizes .el-select .el-input__inner) { color: #c0c4cc !important; height: 22px !important; line-height: 22px !important; font-size: 12px !important; }
  :deep(.el-pagination .el-select__caret) { color: #409eff; }
  
  </style>
  